//
//  WBUserAccount.swift
//  WeiBoApp
//
//  Created by CrazyHacker on 16/7/4.
//  Copyright © 2016年 CrazyHacker. All rights reserved.
//

import UIKit

private let userAccountFile: NSString = "userAccount.json"
class WBUserAccount: NSObject {

    /// 用户令牌 用户授权的唯一票据，用于调用微博的开放接口
    var access_token: String? //= "2.00j8T3WGQDK9mBaa728f0753HTeRgE"
    /// access_token 的失效日期
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }

    /// 用户名
    var screen_name: String?
    /// 用户图像
    var avatar_large: String?
    /// access_token的生命周期
    var remind_in: String?
    /// 授权用户的UID
    var uid: String?
    
    /// 过期日期
    var expiresDate: Date?
    
    // 将用户模型保存到沙盒
    func saveUserAccount() {
        // 模型转字典 转化成json 对象 -- 字典/数组、、、
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        dict.removeValue(forKey: "expires_in")
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
         filePath = userAccountFile.cz_appendDocumentDir() else {
      return
    }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        print(filePath)
    }
   override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        // 检查沙盒是否有数据
        guard let path = userAccountFile.cz_appendDocumentDir(),
            data = NSData(contentsOfFile: path),
            dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [NSObject : AnyObject] else {
                return
        }
        
        
        // 使用字典设置属性的值
      //  expiresDate = NSDate(timeIntervalSinceNow: -3600 * 24) as Date
    // FIXME: 关键代码
        yy_modelSet(with: dict ?? [:])
        if expiresDate?.compare(Date()) != .orderedDescending {
            access_token = nil
            uid = nil
           _ = try? FileManager.default().removeItem(atPath: userAccountFile as String)
        }
        
    }
   
}


